package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.NursingLevelVo;
import com.zzyl.nursing.vo.RoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    // 定义key
    private final String KEY = "zzyl:nursing-room";
    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        deleteCache();
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        deleteCache();
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        deleteCache();
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 查询房间数据(楼层、房间、价格)
     *
     * @param id
     * @return
     */
    @Override
    public RoomVo getRoomData(Long id) {
        BoundValueOperations<String, String> operations = redisTemplate.boundValueOps(KEY);
        // 先从缓存中查询，如果能查到就直接返回，如果查不到就需要从mysql中查询并放入到Redis中
        String str = operations.get();
        // 缓存中找不到
        RoomVo roomVo;
        if (str==null){
            roomVo = roomMapper.getRoomData(id);
            String jsonStr = JSONUtil.toJsonStr(roomVo);
            operations.set(jsonStr);
        }
        // 缓存中可以找到
        else {
            roomVo = JSONUtil.toBean(str, RoomVo.class);
        }
        return roomVo;
    }

    /**
     * 获取房间中的智能设备及数据
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {

        List<RoomVo> roomVoList = roomMapper.getRoomsWithDeviceByFloorId(floorId);
        // 遍历得到每一个房间
        roomVoList.forEach(roomVo -> {
            // 遍历得到房间的设备
            List<DeviceVo> deviceVos = roomVo.getDeviceVos();
            // 房间有设备再进行
            if (CollUtil.isNotEmpty(deviceVos)){
                // 遍历设备集合得到每个设备
                deviceVos.forEach(deviceVo -> {

                    // 从redis获取设备数据
                    String dataStr = (String) redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).get(deviceVo.getIotId());
                    // 转换为List集合
                    List<DeviceData> dataList = JSONUtil.toList(dataStr, DeviceData.class);
                    // 往房间设备中添加设备数据
                    deviceVo.setDeviceDataVos(dataList);
                });
            }
            // 遍历得到每个床位
            List<BedVo> bedVoList = roomVo.getBedVoList();
            // 房间中有床位再进行
            if (CollUtil.isNotEmpty(bedVoList)){
                // 遍历得到床位的数据
                bedVoList.forEach(bedVo -> {
                    List<DeviceVo> deviceVosBed = bedVo.getDeviceVos();
                    // 床位有设备再进行
                    if (CollUtil.isNotEmpty(deviceVosBed)){
                        deviceVosBed.forEach(deviceVo -> {
                            // 从redis获取设备数据
                            String dataStr = (String) redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).get(deviceVo.getIotId());
                            // 转换为List集合
                            List<DeviceData> dataList = JSONUtil.toList(dataStr, DeviceData.class);
                            // 往房间设备中添加设备数据
                            deviceVo.setDeviceDataVos(dataList);
                        });
                    }
                });
            }
        });
        return roomVoList;
    }

    /**
     * 删除缓存
     */
    private void deleteCache() {
        //删除缓存
        redisTemplate.delete(KEY);
    }
}
